package com.ruoyi.web.controller.tool;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.ruoyi.system.domain.vo.AlipayModel;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class AlipayTradeWapPay {

    public static final String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSzTXXL5+EKPOwbRIuR1/yHBeYqp5VYhpXF4IoHeGhQlyUOU1I7ky8WgdDF0Qwm2fczI1Tyh4JnpjGchAIFbZdkLU92xQ/wgoIa5hef+dJ99GMpIi2zafDsQx0+E3HSrNMmHI4d4gaH6eXk8rdRNd3R1E84SUwbJ5sO0HpdmqC0a35yOwh5un4+i6Dl8+OwWnq1sdVrXNHdtYAwteGCIsEFpI3JOyrvV+cp2ptwL5yo3SfN5GLkrMfHIxHz8yNMVvqF1q/8LgRepPLv7b7eMa9j4QZ7GMw10aOVjDoVK6Mdrm4uX6AfcJ0q3yyFhwYI6aKGbJC6N+H3vP3GlDkrdzhAgMBAAECggEAL9Uhl+3ygfN+A5xmciHbh13T6nCdiqCeiIYmaL/jxtGCrOFG516OLkj/WML5+wSIAQ+9dPHEe8nraa28v4WjmDUQeQkrPeMRtdCpIxF14UoYQ0VRLo8v/Llxn6NQZIFYjrqVbQS1mh16VA9Z6GMH+duJAtcxcOfTbtyYC2QELH97YN1BwLgXe075BA7G/FxBJkcbkc359tdKHcbK+l4p22pGhr7ejXQlWr0gTYljopK/SRU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iKn6j/kfjD4RWDaIYJt96RTrDleRkdVfkZKU7tF8qVz4Jq3ehGh3C5/7EAZJmGL5zYIBfDTB9ymlcWgSgxwKTCu3SGMuAyB6FuOZ2USn/EC/Ny6/IU9d++J29gth0bYwN8iRpPmBMPf32woW2h2q3Wfh2UzbYoPwsB5vD1HUB/f0pTPfZC4iQH7femWELsluJwA39wPHwOEfZ3mz00C9UbivpFUXMZDTkrjjcBY6VpvkZZy7UscDZv9OLV5KKEDCgYaT+JcNx+bDqwoPKcq51sDuAZHu1QIn2r0D5uj7vp02F07dDWhQIDAQAB";

    public static final String appId = "2021005114642353";
    public static final String sellerId = "2088660105543554";
    public static final String notifyUrl = "https://8yk.co/mall/order/callback";
    public static final String returnUrl = "https://8yk.co/%s";



    public static void main(String[] args) throws AlipayApiException {
        AlipayModel alipayModel = new AlipayModel();
        alipayModel.setGoodsName("啊啊啊4");
        alipayModel.setMoney(new BigDecimal("0.01"));
        alipayModel.setOrderSn("0791737242411654");
//        String pay = pay(alipayModel);
//        System.out.println(pay);
        refund(alipayModel);
    }

    public static String refund(AlipayModel alipayModel) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();

        // 设置商户订单号
        model.setOutTradeNo(alipayModel.getOrderSn());

        // 设置支付宝交易号
//        model.setTradeNo("2014112611001004680073956707");

        // 设置退款金额
        model.setRefundAmount(alipayModel.getMoney().toString());

        // 设置退款原因说明
        model.setRefundReason("正常退款");

        // 设置退款请求号
        model.setOutRequestNo(String.valueOf(System.currentTimeMillis()));

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradeRefundResponse response = alipayClient.execute(request);

        if (response.isSuccess()) {
            log.info("调用成功");
        } else {
            log.info(response.getBody());
            throw new AlipayApiException("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        log.info(response.getBody());
        return response.getBody();
    }

    public static String pay(AlipayModel alipayModel) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(alipayModel.getOrderSn());
        model.setTotalAmount(alipayModel.getMoney().toString());
        model.setSubject(alipayModel.getGoodsName());
        model.setProductCode("QUICK_WAP_WAY");
        model.setSellerId(sellerId);
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(String.format(returnUrl,alipayModel.getCode()));
//        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
         AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        if (response.isSuccess()) {
            log.info("调用成功");
        } else {
            log.info(response.getBody());
            throw new AlipayApiException("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return response.getBody();
    }

    private static AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(appId);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    public static Map< String , String > check(HttpServletRequest request) throws AlipayApiException {
        Map< String , String > params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean  signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8","RSA2") ;
        //boolean flag = AlipaySignature.rsaCertCheckV1(params,alipayPublicCertPath,"UTF-8","RSA2");
        if (signVerified){
            return params;
        } else {
            return null;
        }
    }
}